
package com.example.ivideo_2211a.commodity
import com.example.ivideo_2211a.commodity.CustomerServiceActivity

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.ActivityGoodsDetailBinding
import kotlinx.coroutines.launch

@Route(path = "/app/GoodsDetailActivity")
class GoodsDetailActivity : AppCompatActivity() {
    override fun onStart() {
        super.onStart()
        // 客服按钮点击跳转到客服页面
        binding.llService.setOnClickListener {
            //startActivity(android.content.Intent(this, CustomerServiceActivity::class.java))
            ARouter.getInstance().build("/app/CustomerServiceActivity").navigation()
        }
    }
    
    private lateinit var binding: ActivityGoodsDetailBinding
    private val commodityApi = CommondityRetrorfit.commodityApi
    
    @Autowired
    @JvmField
    var goodsId=0
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 注入路由参数
        ARouter.getInstance().inject(this)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_goods_detail)
        

        
        // 检查goodsId是否正确传递
        if (goodsId <= 0) {
            ToastUtils.showShort("商品ID无效: $goodsId")
            finish()
            return
        }
        
        ToastUtils.showShort("正在加载商品ID: $goodsId")
        
        // 加载商品详情
        loadGoodsDetail()
    }
    
    private fun loadGoodsDetail() {
        lifecycleScope.launch {
            try {
                // 显示加载状态
                showLoading(true)
                ToastUtils.showShort("开始请求商品详情...")
                
                val response = commodityApi.getGoodsDetail(goodsId)
                
                // 隐藏加载状态
                showLoading(false)
                
                ToastUtils.showShort("API响应码: ${response.code}, 消息: ${response}")
                
                if (response.code == 200) {
                    if (response.data != null) {
                        ToastUtils.showShort("获取到商品数据，开始更新UI")
                        updateUI(response.data)
                    } else {
                        ToastUtils.showShort("API返回成功但数据为空")
                        showErrorState()
                    }
                } else {
                    // 处理业务错误 
                    val errorMsg = when (response.code) {
                        404 -> "商品不存在"
                        500 -> "服务器内部错误"
                        else -> "加载商品详情失败，错误码: ${response.code}, 消息: ${response}"
                    }
                    ToastUtils.showShort(errorMsg)
                    showErrorState()
                }
            } catch (e: Exception) {
                // 隐藏加载状态
                showLoading(false)
                
                // 处理网络异常
                val errorMsg = when {
                    e.message?.contains("timeout") == true -> "请求超时，请检查网络连接"
                    e.message?.contains("Unable to resolve host") == true -> "网络连接失败，请检查网络设置"
                    else -> "网络请求失败: ${e.message}"
                }
                ToastUtils.showShort(errorMsg)
                showErrorState()
            }
        }
    }
    
    private fun showLoading(isLoading: Boolean) {
        // 这里可以显示/隐藏加载进度条
        // 例如：binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
    }
    
    private fun showErrorState() {
        // 这里可以显示错误状态页面
        // 例如：显示重试按钮等
    }
    
    private fun updateUI(goodsDetail: GoodsDrtailData?) {
        if (goodsDetail == null) {
            ToastUtils.showShort("商品数据为空")
            showErrorState()
            return
        }
        
        with(binding) {
            // 设置商品基本信息
            tvGoodsPrice.text = "¥${goodsDetail.goods_default_price ?: 0}"
            tvGoodsName.text = goodsDetail.goods_desc ?: "商品名称"
            tvGoodsAttribute.text = goodsDetail.goods_attribute ?: "商品属性"
            tvSalesCount.text = "月销 ${goodsDetail.goods_sales_count ?: 0} 件"
            tvStockCount.text = "库存 ${goodsDetail.goods_stock_count ?: 0} 件"
            tvGoodsDetailOne.text = goodsDetail.goods_attribute ?: "商品详情描述一"
            //tvGoodsDetailTwo.text = goodsDetail.goods_detail_two ?: "商品详情描述二"
            
            // 设置商品图片轮播
            setupBannerViewPager(goodsDetail.bannerList ?: emptyList())
        }
    }
    
    private fun setupBannerViewPager(bannerList: List<String>?) {
        if (!bannerList.isNullOrEmpty()) {
            val bannerAdapter = GoodsBannerAdapter(bannerList)
            binding.vpGoodsBanner.adapter = bannerAdapter
        } else {
            // 如果没有图片，可以隐藏ViewPager或显示默认图片
            binding.vpGoodsBanner.adapter = null
        }
    }
}